package com.fengyi.library.service.impl;

import com.fengyi.library.service.LoanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 借阅状态更新器
 * 定时任务，用于自动更新借阅状态，特别是将过期未还的借阅标记为逾期状态
 */
@Component
public class LoanStatusUpdater {

    private final LoanService loanService;

    @Autowired
    public LoanStatusUpdater(LoanService loanService) {
        this.loanService = loanService;
    }

    /**
     * 每天凌晨1点执行一次状态更新
     * 检查所有借出但已过期的借阅，将其状态更新为OVERDUE
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void updateLoanStatus() {
        System.out.println("开始执行定时借阅状态更新任务...");
        try {
            loanService.updateLoanStatus();
            System.out.println("借阅状态更新任务完成");
        } catch (Exception e) {
            System.err.println("借阅状态更新失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 立即执行一次借阅状态更新
     * 用于应用启动时或手动触发时调用
     */
    public void updateLoanStatusNow() {
        System.out.println("开始执行即时借阅状态更新...");
        try {
            loanService.updateLoanStatus();
            System.out.println("即时借阅状态更新完成");
        } catch (Exception e) {
            System.err.println("即时借阅状态更新失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
